'use strict';

/**
 * @ngdoc function
 * @name VOA.services:TopicsService
 * @description
 * # TopicsService
 * Topics Service of the VOA app
 */

angular.module('VOA.services')
.factory('Topics', function(ENV, $http, $log,$q) {
  var topics = [];
  var currentTab = 'Technology_Report_1.html';
  var nextPage = 1;
  var hasNextPage = true;
   function ItemModel(id, text, href,type,date){
             this.id = id; 
            this.text = text; 
            this.href = href||""; 
            this.type=type||"";
            this.date=date||"";
            
       }
        
 
  return {
    refresh: function() {
        var url= ENV.api+currentTab;
     var itemArray =[];

     var deferred = $q.defer();
     $http({
              method:'GET',
              url:url
              }).success(function(response,header,config,status){
              //响应成功
                var element = $("#list ul li a",response);
                var  topicsModel={};
                var itemArray =[];
                    var item=null;
                var title= $("#right_box_title a",response).html(); 
                topicsModel.title=title;
                 for(var j=0; j<element.length; j++)
                 {
                     item=new ItemModel();
                         item.type="detail";
                           item.id=j;
                          
                            item.href=$(element[j]).attr("href");
                            item.text =$(element[j]).html();
                           // var text=element[j].children;
                           // item.text=text[0].data+element[j].next.data;
                           var parent=$(element[j]).parent().html();
                          var re=/\(.*\)/;  
                          var date= re.exec(parent);
                     
                          item.date=date[0];
                           itemArray.push(item);
                     
                 }
                topicsModel.itemArray=itemArray;
                deferred.resolve(topicsModel);

              }).error(function(data,header,config,status){
              //处理响应失败
              console.log("get data error");
                deferred.resolve(undefined);
              });
       
      return deferred;
   
    },
   
    currentTab: function(newTab) {
      if (typeof newTab !== 'undefined') {
        currentTab = newTab;
      }
      return currentTab;
    },
   
    getTopics: function() {
      return topics;
    },
    getById: function(id) {

      if (!!topics) {
        for (var i = 0; i < topics.length; i++) {
          if (topics[i].id === id) {
            return topics[i];
          }
        }
      } else {
        return null;
      }
    },

    resetData: function() {
      topics = [];
      nextPage = 1;
      hasNextPage = true;
    },
  };
});
